package com.security.service;

import com.security.constant.AuthConstant;
import com.security.entity.User;
import com.security.entity.UserInfo;
import com.security.feign.ITestUserClient;
import com.security.util.TokenUtil;
import com.security.util.WebUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

	private ITestUserClient userClient;

	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		HttpServletRequest request = WebUtil.getRequest();
		// 获取租户ID
		String headerTenant = request.getHeader(TokenUtil.TENANT_HEADER_KEY);
		String paramTenant = request.getParameter(TokenUtil.TENANT_PARAM_KEY);
		if (StringUtils.isAllBlank(headerTenant, paramTenant)) {
			throw new UserDeniedAuthorizationException(TokenUtil.TENANT_NOT_FOUND);
		}
		UserInfo userInfo = userClient.uInfo(username);
		User user = userInfo.getUser();
		if (user == null || user.getId() == null) {
			throw new UsernameNotFoundException(TokenUtil.USER_NOT_FOUND);
		}
		return new TestUserDetails(user.getId(),
			user.getName(), user.getRealName(),
			username, AuthConstant.ENCRYPT + user.getPassword(), true, true, true, true,
			AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.join(userInfo.getRoles())));
	}

}
